<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2022-01-31
 * Time: 17:58
 */

namespace App\Services\User;
use App\CodeResponse;
use App\Exceptions\BusinessException;
use App\Models\User\User;
use App\Services\BaseServices;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;


class UserServices extends BaseServices
{

    public function getUserById($id)
    {
        return User::find($id);
    }

    public function getUsers(array $userIds) {
        if (empty($userIds)) {
            return collect([]);
        }
        return User::query()->whereIn("id", $userIds)->where('deleted', 0)->get();
    }

    /*
     * 根据用户名获取用户信息
     * @param $username
     * @return User|null|Model
     */
    public function getByUsername($username) {
        return User::query()->where("username",$username)
            ->where("deleted",0)->first();
    }

    /*
     * 根据用户名获取用户信息
     * @param $Mobile
     * @return User|null|Model
     */
    public function getByMobile($mobile) {
        return User::query()->where("mobile",$mobile)
            ->where("deleted",0)->first();
    }

    /**
     * 验证手机号是否达到限制条数
     * @param string $mobile
     * @return bool
     */
    public function checkMobileSendCaptchaCount($mobile) {
        $countKey = "register_captcha_count_".$mobile;
        if (Cache::has($countKey)) {
            $count = Cache::increment($countKey);
            if ($count > 10) {
                return false;
            }
        } else {
            //put()添加数据，数组存在则覆盖 ,第二天0点-当前时间(从当前时间到第二天零点)
            Cache::put($countKey,1,Carbon::tomorrow()->diffInSeconds(now()));
        }
        return true;
    }

    /**
     * 验证短信验证码
     * @param string $mobile
     * @return bool
     */
    public function checkCaptcha($mobile,$code) {
        $key = "register_captcha_".$mobile;
        $isPass = $code === Cache::get($key);
        //验证完后删除对应的值
        if ($isPass) {
            Cache::forget($key);
            return true;
        } else {
            throw new BusinessException(CodeResponse::AUTH_CAPTCHA_UNMATCH);
        }
    }

    public function setCaptcha($mobile) {
        $code = random_int(100000,999999);
        $code = strval($code);
        Cache::put("register_captcha_".$mobile,$code,600);
        return $code;
    }
}